﻿#include <SIX_Utility.h>
#include <SIX_XMLParser.h>
#include <SIX_SystemInfo.h>
#include "SIX_ControlButton.h"
#include "SIX_CallBackBox.h"

#ifdef WIN32
#include <windows.h>
#pragma comment(lib,"Winmm.lib")
#pragma comment(lib,"Iphlpapi.lib")
#endif

#include <math.h>

SIX_Utility *SIX_Utility::m_pUtility = 0;

SIX_MP::SIX_MP()
{
	mp = new MP();
}

SIX_MP::~SIX_MP()
{
	mp->clear();
#ifdef WIN32
	mp->swap(MP());
#endif
	CC_SAFE_DELETE(mp);
}

int SIX_MP::size()
{
	if (mp)
		return mp->size();
	return 0;
}

void SIX_MP::push_back(const char *val)
{
	if (mp)
		mp->push_back(val);
}

void SIX_MP::pop_back()
{
	if (mp)
		mp->pop_back();
}

const char *SIX_MP::at(int idx)
{
	if (mp)
		return mp->at(idx).c_str();
	return 0;
}

// ---------------------------------------
SIX_Utility *SIX_Utility::GetInstance()
{
    if (!m_pUtility)
        m_pUtility = new SIX_Utility();

    return m_pUtility;
}

SIX_Utility::SIX_Utility()
{
#if defined(_WIN32)
	srand((unsigned int)time(0));
	// 先取主频
	LARGE_INTEGER largeInteger;
	QueryPerformanceFrequency(&largeInteger);
	s_invFrequency = double(largeInteger.QuadPart);
	if (s_invFrequency > 0.0)
		s_invFrequency = 1000.0 / s_invFrequency;

	QueryPerformanceCounter(&m_GlobalTimerStart);
#elif defined(__linux__) || defined (__APPLE__)
	gettimeofday(&m_GlobalTimerStart,0);
#endif
}

SIX_Utility::~SIX_Utility()
{
	ReleaseHitBox();
	CC_SAFE_DELETE(pXML);
}

unsigned long SIX_Utility::REVE_DWORD(unsigned long x)
{
#ifdef WIN32
	// 0x12345678 => 0x78563412
	return MAKELONG(MAKEWORD(HIBYTE(HIWORD(x)),LOBYTE(HIWORD(x))),MAKEWORD(HIBYTE(LOWORD(x)),LOBYTE(LOWORD(x))));
#else
	return 0;
#endif
}

unsigned long SIX_Utility::GetCurrentThreadId()
{
#ifdef _WIN32
	return ::GetCurrentThreadId();
#else
	return (unsigned long)pthread_self();
#endif
}

// 生成随机数
int SIX_Utility::RNDNUM(int min,int max)
{
	int rndnum = 0;

	rndnum = rand() % (max-min+1) + min;

	if (rndnum<min)
		rndnum=min;

	return rndnum;
};

int SIX_Utility::getIntPart(double x)
{
    if (x <= 0.0)
       return (int)(ceil(x));

    if (ceil(x) == x)
       x = ceil(x);
    else
       x = ceil(x) - 1;
    return (int)(x);
}

int SIX_Utility::code_convert(const char *from_charset, const char *to_charset, const char *inbuf, size_t inlen, char *outbuf, size_t outlen)
{
    iconv_t cd;

    const char *temp = inbuf;

    const char **pin = &temp;

    char **pout = &outbuf;

    memset(outbuf,0,outlen);

    cd = iconv_open(to_charset,from_charset);

    if(cd==0) 
		return -1;

    if(iconv(cd,pin,&inlen,pout,&outlen)==-1) 
		return -1;

    iconv_close(cd);

    return 0;

}

/*UTF8转GB2312*/
std::string SIX_Utility::U2G(const char *inbuf)
{
	size_t inlen = strlen(inbuf);

	char * outbuf = new char[inlen * 2 + 2];

	std::string strRet;

	if(code_convert("utf-8", "gb2312", inbuf, inlen, outbuf, inlen * 2 + 2) == 0)
	{
		strRet = outbuf;
	}
	else
	{
		// e.g：冇
		if(code_convert("utf-8", "gb18030", inbuf, inlen, outbuf, inlen * 2 + 2) == 0)
			strRet = outbuf;
	}

	delete [] outbuf;

	return strRet;
}

/*GB2312转UTF8*/
std::string SIX_Utility::G2U(const char *inbuf)
{
	size_t inlen = strlen(inbuf);

	char * outbuf = new char[inlen * 2 + 2];
	memset(outbuf, 0, sizeof(char)*(inlen * 2 + 2));

	std::string strRet;

	if(code_convert("gb2312", "utf-8", inbuf, inlen, outbuf, inlen * 2 + 2) == 0)
	{
		strRet = outbuf;
	}
	else
	{
		// e.g：冇
		if (code_convert("gb18030", "utf-8", inbuf, inlen, outbuf, inlen * 2 + 2) == 0)
			strRet = outbuf;
	}

	delete [] outbuf;

	return strRet;
}

wstring SIX_Utility::AnsiToUnicode(const char* buf)
{
#ifdef WIN32
	int len = ::MultiByteToWideChar(CP_ACP, 0, buf, -1, 0, 0);
	if (len == 0) return L"";

	std::vector<wchar_t> unicode(len);
	::MultiByteToWideChar(CP_ACP, 0, buf, -1, &unicode[0], len);
	return &unicode[0];
#else
	return 0;
#endif
}

string SIX_Utility::UnicodeToAnsi(const wchar_t* buf)
{
#ifdef WIN32
	int len = ::WideCharToMultiByte(CP_ACP, 0, buf, -1, 0, 0, 0, 0);
	if (len == 0) return "";

	std::vector<char> utf8(len);
	::WideCharToMultiByte(CP_ACP, 0, buf, -1, &utf8[0], len, 0, 0);

	return &utf8[0];
#else
	return 0;
#endif
}

wstring SIX_Utility::Utf8ToUnicode(const char* buf)
{
#ifdef WIN32
	int len = ::MultiByteToWideChar(CP_UTF8, 0, buf, -1, 0, 0);
	if (len == 0) return L"";

	std::vector<wchar_t> unicode(len);
	::MultiByteToWideChar(CP_UTF8, 0, buf, -1, &unicode[0], len);

	return &unicode[0];
#else
	return 0;
#endif
}

string SIX_Utility::UnicodeToUtf8(const wchar_t* buf)
{
#ifdef WIN32
	int len = ::WideCharToMultiByte(CP_UTF8, 0, buf, -1, 0, 0, 0, 0);
	if (len == 0) return "";

	std::vector<char> utf8(len);
	::WideCharToMultiByte(CP_UTF8, 0, buf, -1, &utf8[0], len, 0, 0);

	return &utf8[0];
#else
	return 0;
#endif
}

int SIX_Utility::Split(char *sp,char *src,SIX_MP *ptr,int SplitCount)
{
	if (!ptr)
		return 0;

	MP *mp = new MP();
	int retv = Split(sp,src,mp,SplitCount);
	if (mp->size())
	{
		for (unsigned int i=0;i<mp->size();i++)
			ptr->push_back(mp->at(i).c_str());
	}

	mp->clear();
#ifdef WIN32
	mp->swap(MP());
#endif
	CC_SAFE_DELETE(mp);

	return retv;
}

int SIX_Utility::Split(char *sp,char *src,MP *ptr,int SplitCount)
{
	if (!ptr)
		return 0;

	int splen = strlen(sp);
	char *ss=src;
	char *p = ss;
	char *last = ss;

	int index =0;
	int pos = 0;

	string tmpbuff("");

	p=strstr(p,sp);

	while (p)
	{
		// 本轮找到sp的位置
		pos = p - last;

		tmpbuff.resize(pos,0);

		memcpy((void*)tmpbuff.c_str(),last,pos);

		ptr->push_back(tmpbuff.c_str());

		p+=splen;
		last = p;

		if (SplitCount>0 && index==SplitCount-1)
		{
			int lastlen = strlen(src) - (last - ss);
			tmpbuff.resize(lastlen,0);
			memcpy((void*)tmpbuff.c_str(),last,lastlen);
			ptr->push_back(tmpbuff.c_str());
			break;
		}

		p=strstr(p,sp);

		if (!p)
		{
			int lastlen = strlen(src) - (last - ss);
			tmpbuff.resize(lastlen,0);
			memcpy((void*)tmpbuff.c_str(),last,lastlen);
			ptr->push_back(tmpbuff.c_str());
		}
		index++;
	}

	index = ptr->size();

	return index;
}

void SIX_Utility::replace(string &strBig,const string &strsrc,const string &strdst)
{
     string::size_type pos = 0;
     while((pos = strBig.find(strsrc,pos))!= string::npos)
     {
         strBig.replace(pos,strsrc.length(),strdst);
         pos += strdst.length();
     }
}

CCPoint SIX_Utility::getAnotherCoordinate(CCPoint pt, float fAngle, int nDistance)
{
	CCPoint ptReturn(0,0);
	fAngle = (float)(fAngle*M_PI/180);
	ptReturn.x = cos(fAngle)*nDistance + pt.x;
	ptReturn.y = sin(fAngle)*nDistance + pt.y;
	return ptReturn;
}

void SIX_Utility::setVisibleAllChildren(CCNode *pRoot,bool bVisible)
{
	if (!pRoot)
		return;
	CCNode *pChild = 0;
	CCARRAY_FOREACH_T(pRoot->getChildren(),pChild,CCNode*)
	{
		if (pChild)
			pChild->setVisible(bVisible);
	}
}

float SIX_Utility::RandomFloat(float lo, float hi)
{
	float r = (float)(std::rand() & (32767));
	r /= 32767;
	r = (hi - lo) * r + lo;
	return r;
}

unsigned long long SIX_Utility::GetTickCount()
{
#ifdef WIN32
	struct __timeb64 tv;
	_ftime64(&tv);
	return tv.time * 1000 + tv.millitm;
#else
	struct timeval tv; 
	gettimeofday(&tv,0);
	return ((unsigned long long)tv.tv_sec)*1000+(unsigned long long)tv.tv_usec/1000;
#endif
}

void SIX_Utility::GetLocalTime(LPSYSTEMTIME st)
{
	if (!st)
		return;

#ifdef WIN32
	::GetLocalTime(st);
#else
	struct timeval tv;
	gettimeofday (&tv , NULL);

	tm tm_now ;
	localtime_r(&tv.tv_sec,&tm_now);

	st->wYear = tm_now.tm_year+1900;
	st->wMonth = tm_now.tm_mon+1;
	st->wDay = tm_now.tm_mday;
	st->wDayOfWeek = (tm_now.tm_wday+1)%7;
	st->wHour =tm_now.tm_hour;
	st->wMinute = tm_now.tm_min;
	st->wSecond = tm_now.tm_sec;
	st->wMilliseconds = tv.tv_usec/1000;
#endif
}

double SIX_Utility::Fixed(double n,int p)
{
	double x = pow(10.0,p);
#ifdef WIN32
	return ((_int64)(n*x+0.5))/x;
#else
	return ((long long)(n*x+0.5))/x;
#endif
}

// 定时器部分
#if defined(_WIN32) && !defined(SHP)

void SIX_Utility::TimerStart()
{
	QueryPerformanceCounter(&m_start);
}

void SIX_Utility::TimerEnd()
{
	QueryPerformanceCounter(&m_end);
}

double SIX_Utility::GetMilliseconds()
{
	return Fixed((s_invFrequency*(m_end.QuadPart-m_start.QuadPart)),4);
}

double SIX_Utility::GetGlobalSecond()
{
	QueryPerformanceCounter(&m_GlobalTimerEnd);
	// 保留小数点后4位
	return Fixed((s_invFrequency*(m_GlobalTimerEnd.QuadPart-m_GlobalTimerStart.QuadPart))/1000.0,4);
}

#elif defined(__linux__) || defined (__APPLE__)

#include <sys/time.h>

void SIX_Utility::TimerStart()
{
	gettimeofday(&m_start,0);
}

void SIX_Utility::TimerEnd()
{
	gettimeofday(&m_end,0);
}

double SIX_Utility::GetMilliseconds()
{
	return (m_end.tv_sec - m_start.tv_sec) * 1000.0f + (m_end.tv_usec - m_start.tv_usec) * 0.001f;
}

double SIX_Utility::GetGlobalSecond()
{
	gettimeofday(&m_GlobalTimerEnd,0);
	return ((m_GlobalTimerEnd.tv_sec - m_GlobalTimerStart.tv_sec) * 1000.0f + (m_GlobalTimerEnd.tv_usec - m_GlobalTimerStart.tv_usec) * 0.001f) / 1000.0f;
}

#else

void SIX_Utility::TimerStart()
{
}

void SIX_Utility::TimerEnd()
{
}

double SIX_Utility::GetMilliseconds()
{
	return 0.0f;
}

double SIX_Utility::GetGlobalSecond()
{
	return 0.0f;
}

#endif

//-- 异步加载plist
//-- 另外还在回调中做以下2步处理：
//-- 1、CCSpriteFrameCache:sharedSpriteFrameCache():addSpriteFramesWithDictionary(dict,pTexture)
//-- 2、CCSpriteFrameCache:sharedSpriteFrameCache():insertPlist(pszPlist)
bool SIX_Utility::addSpriteFramesWithPlistAsync(const char *pszPlist,CCObject *target,SEL_CallFuncO selector)
{
	// -- 先获取全路径
	char pszPath[1024] = {0};
	_snprintf(pszPath,1023,"%s",CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(pszPlist));
	
	// -- 根据plist取得dict，非线程安全
	CCDictionary *dict = CCDictionary::createWithContentsOfFile(pszPath);
	
	// -- 根据metadata取得textureFileName
	CCDictionary *metadataDict = dynamic_cast<CCDictionary*>(dict->objectForKey("metadata"));
	if (!metadataDict)
	{
		SIXLog("addSpriteFramesWithPlistAsync.metadataDict.Nil");
		dict->release();
		return false;
	}
	
	char texturePath[1024] = {0};
	_snprintf(texturePath,1023,"%s",metadataDict->valueForKey("textureFileName")->getCString());
	if (!texturePath)
	{
		SIXLog("addSpriteFramesWithPlistAsync.texturePath.A.Nil");
		dict->release();
		return false;
	}
	
	_snprintf(texturePath,1023,"%s",CCFileUtils::sharedFileUtils()->fullPathFromRelativeFile(texturePath,pszPath));
	if (!texturePath)
	{
		SIXLog("texturePath.B.Nil");
		dict->release();
		return false;
	}
	
	// -- 异步加载
	CCTextureCache::sharedTextureCache()->addImageAsync(texturePath,target,selector);
	
	dict->release();
	
	//SIXLog("[0x%08X]addSpriteFramesWithPlistAsync.pszPlist[%s].Done",SIX_Utility::GetInstance()->GetCurrentThreadId(),pszPlist->getCString());

	return true;
}

int SIX_Utility::s2n(char s)
{
	if (s>=48 && s<=57)
		return s-48;
	else if (s>=65 && s<=70)
		return s-55;
	return 0;
}

// 传入整数，返回个数，计算负号
int SIX_Utility::GetNumberLength(long long number)
{
	int len = /*(number<0)?1:*/0;
	char pNumArr[256] = {0};
	_snprintf(pNumArr,255,"%lld",number);
	string numStr(pNumArr);
	len += numStr.length();
	return len;
}

// 根据数字获取精灵并添加批处理精灵
// Cool.Cat
bool SIX_Utility::AddSpriteBatchNodeByNumber(CCSpriteBatchNode *pBatchNode,const char *file,int cell,float padding,int bitcount,unsigned int num)
{
	if (cell<=0)
	{
		CCAssert(cell>0,"cell must more than zero");
		return false;
	}

	if (!pBatchNode)
	{
		CCAssert(pBatchNode,"pBatchNode nil");
		return false;
	}

	//// 必然被整除
	//int result = (int)(pBatchNode->getTexture()->getContentSize().width)%cell;
	//if (result!=0)
	//{
	//	CCAssert(result==0,"pBatchNode width isn't integer multiple for cell");
	//	return false;
	//}

	// 位宽
	float cell_width = (float)(pBatchNode->getTexture()->getContentSize().width/cell);
	float cell_height = pBatchNode->getTexture()->getContentSize().height;
	char pNumArr[256] = {0};
	_snprintf(pNumArr,255,"%u",num);
	string numStr(pNumArr);
	// 位数不足要补0
	int zerofill = bitcount - numStr.length();
	if (zerofill>0)
		for (int i=0;i<zerofill;i++)
			numStr.insert(0,"0");
	for (unsigned int i=0;i<numStr.length();i++)
	{
		int value = s2n(numStr.at(i));
		CCSprite *pSpr = CCSprite::create(file,CCRect((float)(value*cell_width),0.0f,cell_width,cell_height));
		if (!pSpr)
		{
			CCAssert(pSpr,"pSpr nil");
			continue;
		}
		if (i==0)
			pSpr->setPosition(ccp(i*cell_width-pSpr->getContentSize().width/2,cell_height-pSpr->getContentSize().height/2));
		else
			pSpr->setPosition(ccp(i*(cell_width+padding)-pSpr->getContentSize().width/2,cell_height-pSpr->getContentSize().height/2));
		//pSpr->ignoreAnchorPointForPosition(true);
		pBatchNode->addChild(pSpr);
	}
	return true;
}

// -- 重复执行
CCAction *SIX_Utility::schedule(CCNode *node, SEL_CallFunc callback, float delay)
{
    CCDelayTime *pDelay = CCDelayTime::create(delay);
    CCCallFunc *callfunc = CCCallFunc::create(node,callback);
    CCActionInterval *sequence = dynamic_cast<CCActionInterval*>(CCSequence::createWithTwoActions(pDelay, callfunc));
    CCRepeatForever *action = CCRepeatForever::create(sequence);
    node->runAction(action);
    return action;
}

CCAction *SIX_Utility::schedule(CCNode *node, SEL_CallFuncN callback, float delay)
{
    CCDelayTime *pDelay = CCDelayTime::create(delay);
    CCCallFuncN *callfunc = CCCallFuncN::create(node,callback);
    CCActionInterval *sequence = dynamic_cast<CCActionInterval*>(CCSequence::createWithTwoActions(pDelay, callfunc));
    CCRepeatForever *action = CCRepeatForever::create(sequence);
    node->runAction(action);
    return action;
}

// -- 执行一次
CCAction *SIX_Utility::performWithDelay(CCNode *node, SEL_CallFunc callback, float delay)
{
    CCDelayTime *pDelay = CCDelayTime::create(delay);
    CCCallFunc *callfunc = CCCallFunc::create(node,callback);
    CCSequence *sequence = CCSequence::createWithTwoActions(pDelay, callfunc);
    node->runAction(sequence);
    return sequence;
}

CCAction *SIX_Utility::performWithDelay(CCNode *node, SEL_CallFuncN callback, float delay)
{
    CCDelayTime *pDelay = CCDelayTime::create(delay);
    CCCallFuncN *callfunc = CCCallFuncN::create(node,callback);
    CCSequence *sequence = CCSequence::createWithTwoActions(pDelay, callfunc);
    node->runAction(sequence);
    return sequence;
}

bool SIX_Utility::LoadHitBoxFromFile(const char *pccPath)
{
	//SIXLog("TID[0x%08X].LoadHitBoxFromFile.Begin[%s]",this->GetCurrentThreadId(),pccPath);
	unsigned long len = 0;
	const char *pFullPath = CCFileUtils::sharedFileUtils()->fullPathFromRelativePath(pccPath,true);
	unsigned char *pXMLData = CCFileUtils::sharedFileUtils()->getFileData(pFullPath,"rb",&len);
//	string pFileName(pFullPath);
//#ifdef WIN32
//	CC_SAFE_DELETE(pFullPath);
//#endif
	TiXmlDocument *xmlDoc = new TiXmlDocument();
	//if (!xmlDoc->LoadFile(pFileName.c_str()))
	//{
	//	SIXLog("导入配置文件失败！");
	//	CC_SAFE_DELETE(xmlDoc);
	//	return false;
	//}
	xmlDoc->Parse((const char*)pXMLData,0,TIXML_ENCODING_UNKNOWN);
	if (xmlDoc->ErrorId()!=0)
	{
		SIXLog("Load.A.Parse.len[%lu].Error[%d]=%s",len,xmlDoc->ErrorId(),xmlDoc->ErrorDesc());
		CC_SAFE_DELETE_ARRAY(pXMLData);
		CC_SAFE_DELETE(xmlDoc);
		return false;
	}
	CC_SAFE_DELETE_ARRAY(pXMLData);
	TiXmlElement *rootElement = xmlDoc->RootElement();
	ParseXML(rootElement);
	CC_SAFE_DELETE(xmlDoc);
	//SIXLog("TID[0x%08X].LoadHitBoxFromFile.End[%s]",this->GetCurrentThreadId(),pccPath);
	return true;
}

void SIX_Utility::ParseXML(TiXmlElement *rootElement)
{
	if (!rootElement)
		return;

#if (1)
	// 解析效率优化
	// Cool.Cat
	TiXmlNode* pChild = rootElement->FirstChildElement("Sprite");
	if (!pChild)
		return;

	TiXmlElement* pFrameNode = pChild->FirstChildElement("Frames");
	if (!pFrameNode)
		return;

	for(pFrameNode;pFrameNode;pFrameNode=pFrameNode->NextSiblingElement("Frames"))
	{
		const char *attrName=pFrameNode->Attribute("name");
		if (!attrName)
			continue;

		TiXmlElement* pPosNode = pFrameNode->FirstChildElement("Pos");
		if (!pPosNode)
			continue;

		HITBOX_MAP *pHBox = new HITBOX_MAP();
		frameHBox.insert(FHITBOX_MAP::value_type(attrName,pHBox));

		for(pPosNode;pPosNode;pPosNode=pPosNode->NextSiblingElement("Pos"))
		{
			POINT_INFO *pPoint = new POINT_INFO();
			const char *attrIdx=pPosNode->Attribute("idx");
			if (!attrIdx)
			{
				CC_SAFE_DELETE(pPoint);
				continue;
			}
			const char *attrX=pPosNode->Attribute("x");
			if (!attrX)
			{
				CC_SAFE_DELETE(pPoint);
				continue;
			}
			const char *attrY=pPosNode->Attribute("y");
			if (!attrY)
			{
				CC_SAFE_DELETE(pPoint);
				continue;
			}
			pPoint->x = (float)atof(attrX);
			pPoint->y = (float)atof(attrY);
			pHBox->insert(HITBOX_MAP::value_type(atoi(attrIdx),pPoint));
		}
	}
#else
	TiXmlNode* pchild = rootElement->FirstChild();

	while (pchild)
	{
		if (!STRCMP(pchild->Value(),"Sprite"))
		{
			switch( pchild->Type())
			{
			case TiXmlNode::TINYXML_ELEMENT:
				{
					TiXmlNode* pFrameNode = pchild->FirstChild();
					while (pFrameNode)
					{
						// 查找Frame Name属性
						TiXmlAttribute* attrFrameName = pFrameNode->ToElement()->FirstAttribute();
						if(attrFrameName)
						{
							HITBOX_MAP *pHBox = new HITBOX_MAP();
							frameHBox.insert(FHITBOX_MAP::value_type(attrFrameName->Value(),pHBox));

							// 查找Pos节点
							TiXmlNode* pPosNode = pFrameNode->FirstChild();
							while (pPosNode)
							{
								// 查找Pos属性
								int idx = 0;
								POINT_INFO *pPoint = new POINT_INFO();
								TiXmlAttribute* attrPos = pPosNode->ToElement()->FirstAttribute();
								while (attrPos)
								{
									if (!STRCMP(attrPos->Name(),"idx"))
									{
										idx = atoi(attrPos->Value());									
									}
									else if (!STRCMP(attrPos->Name(),"x"))
									{
										pPoint->x = (float)atof(attrPos->Value());
									}
									else if (!STRCMP(attrPos->Name(),"y"))
									{
										pPoint->y = (float)atof(attrPos->Value());
									}
									attrPos = attrPos->Next();
								}

								pHBox->insert(HITBOX_MAP::value_type(idx,pPoint));
								
								pPosNode = pPosNode->NextSibling();
							}
						}
						// 下一个相邻节点
						pFrameNode = pFrameNode->NextSibling();
					}
					break;
				}
			}
		}
		// 下一个相邻节点
		pchild = pchild->NextSibling();
	}
#endif
}

HITBOX_MAP *SIX_Utility::GetHitBoxByFrameName(const char *frameName)
{
	if (!frameName)
		return 0;

	FHITBOX_ITER iter = frameHBox.find(frameName);
	if (iter==frameHBox.end())
		return 0;
	return iter->second;
}

void SIX_Utility::AddHitBox()
{
	for (FHITBOX_ITER iter = frameHBox.begin();iter!=frameHBox.end();)
	{
		HITBOX_MAP *pHitBox = iter->second;
		CCSpriteFrame *pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(iter->first.c_str());
		if (pFrame)
		{
			//pFrame->getTexture()->setHitBox(pHitBox);
			pFrame->setObjName(iter->first.c_str());
			pFrame->setHitBox(pHitBox);
			frameHBox.erase(iter++);
			// pHitBox会在pFrame析构时销毁，所以不用在这里销毁
			// Cool.Cat
			//CC_SAFE_DELETE(pHitBox);
		}
		// 如果frame不存在，说明HBox配置文件有错误，我们就在这里先销毁
		else
		{
			frameHBox.erase(iter++);
			CC_SAFE_DELETE(pHitBox);
		}
	}
}

// 实际上这个函数只有当AddHitBox未调用时才有意义，可以释放掉HBox占用的map内存及自身指针；
// 如果已经调用了AddHitBox，那么在当时已经把HBox占用的map内存释放掉了，所以在这种情况下无意义。
// Cool.Cat
void SIX_Utility::ReleaseHitBox()
{
	for (FHITBOX_ITER iter = frameHBox.begin();iter!=frameHBox.end();)
	{
		HITBOX_MAP *pHitBox = iter->second;
		frameHBox.erase(iter++);
		CC_SAFE_DELETE(pHitBox);
	}
}

// 2D/3D纹理抗锯齿(文字)
void SIX_Utility::FixedTextTexParameters(CCTexture2D *pTexture)
{
#ifdef WIN32
	if (!pTexture)
		return;

	// 使用setAliasTexParameters
	//pTexture->generateMipmap();
	//ccTexParams tp = {GL_LINEAR_MIPMAP_LINEAR,GL_LINEAR,GL_CLAMP_TO_EDGE,GL_CLAMP_TO_EDGE};
	//pTexture->setTexParameters(&tp);
	pTexture->setAliasTexParameters();
#endif
}

// 2D/3D纹理抗锯齿(图片)
void SIX_Utility::FixedImageTexParameters(CCTexture2D *pTexture)
{
	if (!pTexture)
		return;

	ccDirectorProjection mProjection = CCDirector::sharedDirector()->getProjection();
	if (mProjection==kCCDirectorProjection3D || mProjection==kCCDirectorProjectionDefault)
	{
		pTexture->setAntiAliasTexParameters();
	}
	else
	{
		pTexture->setAliasTexParameters();
	}
}

string SIX_Utility::NTOA(long long ip)
{
	struct in_addr in;
	memcpy(&in,&ip,4);
	return string(inet_ntoa(in));
}

bool SIX_Utility::IsSceneRunning(CCNode *pUIScene,const char *SceneName)
{
	if(!pUIScene || (pUIScene && !pUIScene->isRunning()) || !SceneName)
		return false;

	// 要检查是否在游戏场景
	CCScene *pScene = CCDirector::sharedDirector()->getRunningScene();
	if (!pScene)
		return false;
	if (!pScene->getChildren())
		return false;
	CCObject *pObject = pScene->getChildren()->objectAtIndex(0);
	if (!pObject)
		return false;
	if (STRCMP(pObject->getObjName(),SceneName))
		return false;
	return true;
}

CCControlButton *SIX_Utility::CreateButtonWithFrameName(const char *pszSpriteFrameName)
{
	CCControlButton *pBtn = 0;
	if (!pszSpriteFrameName)
		return pBtn;
	CCSpriteFrame *pFrame = CCSpriteFrameCache::sharedSpriteFrameCache()->spriteFrameByName(pszSpriteFrameName);
    if (!pFrame)
		return 0;
	CCScale9Sprite *pScale9Sprite = CCScale9Sprite::createWithSpriteFrame(pFrame);
	if (!pScale9Sprite)
		return 0;
	pBtn = CCControlButton::create(pScale9Sprite);
	if (!pBtn)
		return 0;
	pBtn->ignoreAnchorPointForPosition(true);
	pBtn->setZoomFactor(1.05f);
	pBtn->setPreferredSize(pFrame->getOriginalSize());
	return pBtn;
}

CCControlButton *SIX_Utility::CreateButtonWithFile(const char *file,CCRect rc,const char *text,const char *fontName,int fontSize)
{
	CCControlButton *pBtn = 0;
	if (!file)
		return pBtn;

	CCScale9Sprite *pScale9Sprite = 0;
	if (rc.equals(CCRectZero))
		pScale9Sprite = CCScale9Sprite::create(file);
	else
		pScale9Sprite = CCScale9Sprite::create(file,rc);
	if (!pScale9Sprite)
		return 0;
	if (!text)
		pBtn = CCControlButton::create(pScale9Sprite);
	else
	{
		CCLabelTTF *pTextTTF = CCLabelTTF::create(SIX_Utility::GetInstance()->G2U(text).c_str(),fontName,(float)fontSize);
		pBtn = CCControlButton::create(pTextTTF,pScale9Sprite);
		SIX_Utility::GetInstance()->FixedTextTexParameters(pTextTTF->getTexture());
	}
	if (!pBtn)
		return 0;
	pBtn->ignoreAnchorPointForPosition(true);
	pBtn->setZoomFactor(1.05f);
	pBtn->setPreferredSize(pScale9Sprite->getOriginalSize());
	return pBtn;
}

CCControlButton *SIX_Utility::CreateButtonWithFileCell(const char *file,int cell,bool Hor)
{
	CCControlButton *pBtn = 0;
	if (!file || cell<=1 || cell>=5)
		return pBtn;

	// 四态九宫格
	CCScale9Sprite *pScale9SpriteNor = 0;
	CCScale9Sprite *pScale9SpriteHov = 0;
	CCScale9Sprite *pScale9SpriteSel = 0;
	CCScale9Sprite *pScale9SpriteDis = 0;

	float cell_width = 0.0f;
	float cell_height = 0.0f;
	if (!SplitSpriteWithCell(file,&pScale9SpriteNor,&pScale9SpriteHov,&pScale9SpriteSel,&pScale9SpriteDis,&cell_width,&cell_height,cell,Hor))
		return 0;

	// 必须要有常态，且长宽均不为零
	if (!pScale9SpriteNor || cell_width==0.0f || cell_height==0.0f)
		return 0;

	// 以常态创建按钮先~
	pBtn = CCControlButton::create(pScale9SpriteNor);
	if (!pBtn)
		return pBtn;

	// 高亮
	if (pScale9SpriteHov)
		pBtn->setBackgroundSpriteForState(pScale9SpriteHov,CCControlStateHighlighted);
	// 选中
	if (pScale9SpriteSel)
		pBtn->setBackgroundSpriteForState(pScale9SpriteSel,CCControlStateSelected);
	// 禁用
	if (pScale9SpriteDis)
		pBtn->setBackgroundSpriteForState(pScale9SpriteDis,CCControlStateDisabled);

	pBtn->ignoreAnchorPointForPosition(true);
	pBtn->setZoomFactor(1.05f);
	pBtn->setPreferredSize(CCSize(cell_width,cell_height));
	return pBtn;
}

void SIX_Utility::setMirror(CCScale9Sprite *pScale9Sprite,bool mirrorX,bool mirrorY)
{
	if (!pScale9Sprite)
		return;

	// X轴镜像
	if (mirrorX)
	{
		pScale9Sprite->topLeft->setFlipY(true);
		pScale9Sprite->top->setFlipY(true);
		pScale9Sprite->topRight->setFlipY(true);
		pScale9Sprite->left->setFlipY(true);
		pScale9Sprite->centre->setFlipY(true);
		pScale9Sprite->right->setFlipY(true);
		pScale9Sprite->bottomLeft->setFlipY(true);
		pScale9Sprite->bottom->setFlipY(true);
		pScale9Sprite->bottomRight->setFlipY(true);

		// 上下交换
		CC_SWAP(pScale9Sprite->topLeft,pScale9Sprite->bottomLeft,CCSprite*);
		CC_SWAP(pScale9Sprite->top,pScale9Sprite->bottom,CCSprite*);
		CC_SWAP(pScale9Sprite->topRight,pScale9Sprite->bottomRight,CCSprite*);
	}

	// Y轴镜像
	if (mirrorY)
	{
		pScale9Sprite->topLeft->setFlipX(true);
		pScale9Sprite->top->setFlipX(true);
		pScale9Sprite->topRight->setFlipX(true);
		pScale9Sprite->left->setFlipX(true);
		pScale9Sprite->centre->setFlipX(true);
		pScale9Sprite->right->setFlipX(true);
		pScale9Sprite->bottomLeft->setFlipX(true);
		pScale9Sprite->bottom->setFlipX(true);
		pScale9Sprite->bottomRight->setFlipX(true);

		// 左右交换
		CC_SWAP(pScale9Sprite->topLeft,pScale9Sprite->topRight,CCSprite*);
		CC_SWAP(pScale9Sprite->left,pScale9Sprite->right,CCSprite*);
		CC_SWAP(pScale9Sprite->bottomLeft,pScale9Sprite->bottomRight,CCSprite*);
	}
}

CCControlButton *SIX_Utility::CreateButtonWithFileCell(CCNode* label, const char *file,int cell,bool Hor)
{
	CCControlButton *pBtn = 0;
	if (!file || cell<=1 || cell>=5)
		return pBtn;

	// 四态九宫格
	CCScale9Sprite *pScale9SpriteNor = 0;
	CCScale9Sprite *pScale9SpriteHov = 0;
	CCScale9Sprite *pScale9SpriteSel = 0;
	CCScale9Sprite *pScale9SpriteDis = 0;

	float cell_width = 0.0f;
	float cell_height = 0.0f;
	if (!SplitSpriteWithCell(file,&pScale9SpriteNor,&pScale9SpriteHov,&pScale9SpriteSel,&pScale9SpriteDis,&cell_width,&cell_height,cell,Hor))
		return 0;

	// 必须要有常态，且长宽均不为零
	if (!pScale9SpriteNor || cell_width==0.0f || cell_height==0.0f)
		return 0;

	// 以常态创建按钮先~
	pBtn = CCControlButton::create(label, pScale9SpriteNor);
	if (!pBtn)
		return pBtn;

	// 高亮
	if (pScale9SpriteHov)
		pBtn->setBackgroundSpriteForState(pScale9SpriteHov,CCControlStateHighlighted);
	// 选中
	if (pScale9SpriteSel)
		pBtn->setBackgroundSpriteForState(pScale9SpriteSel,CCControlStateSelected);
	// 禁用
	if (pScale9SpriteDis)
		pBtn->setBackgroundSpriteForState(pScale9SpriteDis,CCControlStateDisabled);

	pBtn->ignoreAnchorPointForPosition(true);
	pBtn->setZoomFactor(1.05f);
	pBtn->setPreferredSize(CCSize(cell_width,cell_height));
	return pBtn;
}

bool SIX_Utility::SplitSpriteWithCell(const char *file,CCScale9Sprite **Nor,CCScale9Sprite **Hov,CCScale9Sprite **Sel,CCScale9Sprite **Dis,float *cell_width,float *cell_height,int cell,bool IsHor)
{
	if (*Nor || *Hov || *Sel || *Dis)
		return false;

	CCTexture2D *pTexture = CCTextureCache::sharedTextureCache()->addImage(file);
	float width = pTexture->getContentSize().width;
	float height = pTexture->getContentSize().height;
	*cell_width = width;
	*cell_height = height;

	// 横向切割
	if (IsHor)
	{
		*cell_width = width/cell;
		for (int i=0;i<cell;i++)
		{
			CCRect rect = CCRectZero;
			rect.origin.x = (i * width)/cell;
			rect.origin.y = 0;
			rect.size.width = *cell_width;
			rect.size.height = height;
			CCSpriteFrame *pFrame = CCSpriteFrame::createWithTexture(pTexture,rect);

			if (i==0)
				*Nor = CCScale9Sprite::createWithSpriteFrame(pFrame);
			else if (i==1)
				*Hov = CCScale9Sprite::createWithSpriteFrame(pFrame);
			else if (i==2)
				*Sel = CCScale9Sprite::createWithSpriteFrame(pFrame);
			else if (i==3)
				*Dis = CCScale9Sprite::createWithSpriteFrame(pFrame);
		}
	}
	// 纵向切割
	else
	{
		*cell_height = height/cell;
		for (int i=0;i<cell;i++)
		{
			CCRect rect = CCRectZero;
			rect.origin.x = 0;
			rect.origin.y = (i * height)/cell;
			rect.size.width = width;
			rect.size.height = *cell_height;
			CCSpriteFrame *pFrame = CCSpriteFrame::createWithTexture(pTexture,rect);

			if (i==0)
				*Nor = CCScale9Sprite::createWithSpriteFrame(pFrame);
			else if (i==1)
				*Hov = CCScale9Sprite::createWithSpriteFrame(pFrame);
			else if (i==2)
				*Sel = CCScale9Sprite::createWithSpriteFrame(pFrame);
			else if (i==3)
				*Dis = CCScale9Sprite::createWithSpriteFrame(pFrame);
		}	
	}
	return true;
}

void SIX_Utility::CreateSixButtonWithFileCell(SIX_ControlButton ** pButton, const char *file,int cell,bool Hor/*=true*/)
{
	SIX_ControlButton *pBtn = 0;
	if (!file || cell<=1 || cell>=5)
		return;

	// 四态九宫格
	CCScale9Sprite *pScale9SpriteNor = 0;
	CCScale9Sprite *pScale9SpriteHov = 0;
	CCScale9Sprite *pScale9SpriteSel = 0;
	CCScale9Sprite *pScale9SpriteDis = 0;

	float cell_width = 0.0f;
	float cell_height = 0.0f;
	if (!SIX_Utility::GetInstance()->SplitSpriteWithCell(file,&pScale9SpriteNor,&pScale9SpriteHov,&pScale9SpriteSel,&pScale9SpriteDis,&cell_width,&cell_height,cell,Hor))
		return;

	// 必须要有常态，且长宽均不为零
	if (!pScale9SpriteNor || cell_width==0.0f || cell_height==0.0f)
		return;

	// 以常态创建按钮先~
	pBtn = SIX_ControlButton::create(pScale9SpriteNor);
	if (!pBtn)
		return;

	// 高亮
	if (pScale9SpriteHov)
		pBtn->setBackgroundSpriteForState(pScale9SpriteHov,CCControlStateHighlighted);
	// 选中
	if (pScale9SpriteSel)
		pBtn->setBackgroundSpriteForState(pScale9SpriteSel,CCControlStateSelected);
	// 禁用
	if (pScale9SpriteDis)
		pBtn->setBackgroundSpriteForState(pScale9SpriteDis,CCControlStateDisabled);

	pBtn->ignoreAnchorPointForPosition(true);
	pBtn->setZoomFactor(1.05f);
	pBtn->setPreferredSize(CCSize(cell_width,cell_height));
	*pButton = pBtn;
}

SIX_ControlButton *SIX_Utility::CreateSixButtonWithFile(const char *norFile,const char *horFile,const char *horLabelFile,const CCRect &rcNor/*=CCRectZero*/, const CCRect &rcHor/*=CCRectZero*/, const CCRect &horLabel/*=CCRectZero*/)
{
	return SIX_Utility::CreateSixButtonWithFile(norFile, horFile, 0, horLabelFile, rcNor, rcHor, CCRectZero, horLabel);
}

SIX_ControlButton *SIX_Utility::CreateSixButtonWithFile(const char *norFile,const char *horFile,const char *norLabelFile,const char *horLabelFile,const CCRect &rcNor/*=CCRectZero*/, const CCRect &rcHor/*=CCRectZero*/, const CCRect &norLabel/*=CCRectZero*/, const CCRect &horLabel/*=CCRectZero*/)
{
	SIX_ControlButton *pBtn = 0;
	if (!norFile  ||  !horFile)
		return pBtn;

	CCScale9Sprite *pScale9Sprite = 0;
	CCScale9Sprite *pScale9HorSprite = 0;
	CCSprite *pHorLabel = 0, *pNorLabel = 0;

	if (rcNor.equals(CCRectZero))
		pScale9Sprite = CCScale9Sprite::create(norFile);
	else
		pScale9Sprite = CCScale9Sprite::create(norFile,rcNor);
	if (!pScale9Sprite)
		return 0;

	if (rcHor.equals(CCRectZero))
		pScale9HorSprite = CCScale9Sprite::create(horFile);
	else
		pScale9HorSprite = CCScale9Sprite::create(horFile,rcHor);
	if (!pScale9HorSprite)
		return 0;

	if (norLabelFile)
	{
		if (norLabel.equals(CCRectZero))
			pNorLabel = CCSprite::create(norLabelFile);
		else
			pNorLabel = CCSprite::create(norLabelFile,norLabel);
	}
	if (horLabelFile)
	{
		if (horLabel.equals(CCRectZero))
			pHorLabel = CCSprite::create(horLabelFile);
		else
			pHorLabel = CCSprite::create(horLabelFile,horLabel);
	}

	pBtn = SIX_ControlButton::create(pScale9Sprite);

	if (!pBtn)
		return 0;
		
	pBtn->setBackgroundSpriteForState(pScale9HorSprite,CCControlStateHighlighted);
	pBtn->ignoreAnchorPointForPosition(true);
	pBtn->setZoomFactor(1.05f);
	pBtn->setPreferredSize(pScale9Sprite->getOriginalSize());

	if (pNorLabel)
	{
		FatherCenterAlignment(pNorLabel, pScale9Sprite);
		pScale9Sprite->addChild(pNorLabel);
	}
	if (pHorLabel)
	{
		FatherCenterAlignment(pHorLabel, pScale9HorSprite);
		pScale9HorSprite->addChild(pHorLabel);
	}
	return pBtn;
}

void SIX_Utility::MsgBox(const char * pszMsg, const char * pszTitle/*=0*/)
{
//	CCString *pTitle = 0;
//	if (!pszTitle)
//		pTitle = CCString::create(/*提示*/XorStr<0x0F,5,0x13A09885>("\xC3\xF1\xDB\xAC"+0x13A09885).s);
//	else
//		pTitle = CCString::createWithFormat("%s", pszTitle);
//
////#ifdef WIN32
////	CCMessageBox(pszMsg, pTitle->getCString());
////#else
////	CCMessageBox(SIX_Utility::GetInstance()->G2U(pszMsg).c_str(), SIX_Utility::GetInstance()->G2U(pTitle->getCString()).c_str());
////#endif

	// 要检查是否在游戏场景
	CCScene *pScene = CCDirector::sharedDirector()->getRunningScene();
	if (!pScene)
		return;
	if (!pScene->getChildren())
		return;
	CCObject *pObject = pScene->getChildren()->objectAtIndex(0);
	if (!pObject)
		return;

	SIX_CallBackBox *pBox = SIX_CallBackBox::Create(0.0,0.0,ccc4(0,0,0,0),494,133);
	pBox->setObjectsPointer((CCNode**)&pBox);
	pBox->InitMask(ccc4(0,0,0,128));

	// 显示背景+确定按妞
	pBox->backgroundWithFile("promptBG.png");
	pBox->setClickClose(true);
	//pBox->backgroundWithFile("box_bg_small.png");
	//pBox->buttonSubmitWithFile("box_bt_small.png");
	//pBox->GetBtnSubmit()->setPosition(ccp(112,25));
	//pBox->GetBtnSubmit()->setZoomOnTouchDown(false);
	//CCSprite*pSubmitLabel = CCSprite::create("OkBT.png");
	//FatherCenterAlignment(pSubmitLabel, pBox->GetBtnSubmit());
	//pBox->GetBtnSubmit()->addChild(pSubmitLabel);

	// 显示文字提示
	pBox->setTextAttribute(46,37,407,60,"宋体",20);
#if (CC_TARGET_PLATFORM!=CC_PLATFORM_IOS)
	pBox->setTextAttribute(46,37,407,60,"微软雅黑",20);
#endif
	pBox->getTTF()->setVerticalAlignment(kCCVerticalTextAlignmentCenter);
	pBox->setString(SIX_Utility::GetInstance()->G2U(pszMsg).c_str());
	// 设置可拖拽
	pBox->setAllowDragged(false);

#if (CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
    if (SIX_CCIOSHelper::GetInstance()->getIPhoneType()>=IPHONE_3)
        pBox->setNormalScale(0.7f);
#endif
	pBox->Show(true);
}

void SIX_Utility::MsgBoxEx(const char * pszMsg, const char * pszTitle/*=0*/)
{
	//CCString *pTitle = 0;
	//if (!pszTitle)
	//	pTitle = CCString::create(/*提示*/XorStr<0x0F,5,0x13A09885>("\xC3\xF1\xDB\xAC"+0x13A09885).s);
	//else
	//	pTitle = CCString::createWithFormat("%s", pszTitle);

	////#ifdef WIN32
	////	CCMessageBox(pszMsg, pTitle->getCString());
	////#else
	////	CCMessageBox(SIX_Utility::GetInstance()->G2U(pszMsg).c_str(), SIX_Utility::GetInstance()->G2U(pTitle->getCString()).c_str());
	////#endif

	// 要检查是否在游戏场景
	CCScene *pScene = CCDirector::sharedDirector()->getRunningScene();
	if (!pScene)
		return;
	if (!pScene->getChildren())
		return;
	CCObject *pObject = pScene->getChildren()->objectAtIndex(0);
	if (!pObject)
		return;

	float fWidth = 546.0f;
	float fHeight = 252.0f;

	SIX_CallBackBox *pBox = SIX_CallBackBox::Create(0.0,0.0,ccc4(0,0,0,0),fWidth,fHeight);
	pBox->setObjectsPointer((CCNode**)&pBox);
	pBox->InitMask(ccc4(0,0,0,128));

	// 显示背景+确定按妞
	//pBox->backgroundWithFile("box_bg_small.png");
	CCSprite *pLeftBG = CCSprite::create("box_small_wnd_BG.png");
	pLeftBG->ignoreAnchorPointForPosition(true);
	pLeftBG->setPosition(ccp(0,0));
	pBox->addChild(pLeftBG);
	CCSprite *pRightBG = CCSprite::create("box_small_wnd_BG.png");
	pRightBG->ignoreAnchorPointForPosition(true);
	pRightBG->setFlipX(true);
	pRightBG->setPosition(ccp(fWidth-pRightBG->getContentSize().width,0));
	pBox->addChild(pRightBG);

	pBox->buttonSubmitWithFile("box_bt_small.png");
	pBox->GetBtnSubmit()->setPosition(ccp((fWidth-pBox->GetBtnSubmit()->getContentSize().width)/2,25));
	pBox->GetBtnSubmit()->setZoomOnTouchDown(false);
	CCSprite*pSubmitLabel = CCSprite::create("OkBT.png");
	FatherCenterAlignment(pSubmitLabel, pBox->GetBtnSubmit());
	pBox->GetBtnSubmit()->addChild(pSubmitLabel);

	// 显示文字提示
	pBox->setTextAttribute(46,90,455,120,"宋体",24, kCCTextAlignmentCenter);
	pBox->getTTF()->setVerticalAlignment(kCCVerticalTextAlignmentCenter);
#if (CC_TARGET_PLATFORM!=CC_PLATFORM_IOS)
	pBox->getTTF()->setFontName(/*微软雅黑*/XorStr<0x4D,9,0xB75C340A>("\x83\xEC\x87\xBD\x80\x97\xE9\x8E"+0xB75C340A).s);
#endif
	pBox->setString(SIX_Utility::GetInstance()->G2U(pszMsg).c_str());
	// 设置可拖拽
	pBox->setAllowDragged(false);

	pBox->Show(true);
}

bool SIX_Utility::CheckIDCardIsValid(const char* pszSrc, int iLen)
{
	int iS = 0;
	int iW[]={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
	static char szVerCode[]="10X98765432";

	for(int i=0;i<17;i++)
	{
		iS += (int)(pszSrc[i]-'0') * iW[i];
	}

	int iY = iS%11;
	//printf("%d %% 11 = iY = %d ",iS, iY);
	//printf("%c  ",szVerCode[iY]);

	char cLastChar = *(pszSrc + iLen - 1);
	return szVerCode[iY]==cLastChar;
}

bool SIX_Utility::getStringValue(string strString, string strKey, int &return1, int &return2)
{
	return1 = 0;
	return2 = 0;
	string::size_type index = strString.find(strKey);
	if (index == string::npos)
	{
		return false;
	}

	return1 = atoi(strString.substr(0, index+1).c_str());
	return2 = atoi(strString.substr(index+1, strString.length()-index-1).c_str());
	return true;
}

bool SIX_Utility::getStringValue(string strString, string strKey, long long &return1, long long &return2)
{
	return1 = 0;
	return2 = 0;
	string::size_type index = strString.find(strKey);
	if (index == string::npos)
	{
		return false;
	}

	return1 = ATOI64(strString.substr(0, index+1).c_str());
	return2 = ATOI64(strString.substr(index+1, strString.length()-index-1).c_str());
	return true;
}

int SIX_Utility::countAppearNumber(string strOriginal, string strFind)
{
	int iPos = -1;
	int iCount = 0;

	do
	{
		iPos = strOriginal.find(strFind.c_str(), iPos + 1);
		if (iPos == strOriginal.npos)
			break;

		iCount++;
	} while (1);

	return iCount;
}

int SIX_Utility::countAppearPos(string strOriginal, string strFind, int iPos)
{
	int iTmpPos = -1;
	int iCount = 0;
	do
	{
		iTmpPos = strOriginal.find(strFind.c_str(), iTmpPos + 1);
		iCount++;

		if (iPos == iCount)
			return iTmpPos;

	} while (iTmpPos != strOriginal.npos);

	return -1;
}

void SIX_Utility::subChineseChar(char *pContent, int length, int iCount, bool bIsHaveEllipsis/*=false*/, int *pReturnPos/*=0*/)
{
	//SIXLog("subChineseChar start iCount.[%s],length.[%d], iCount.[%d], Ellipsis.[%d]", pContent,length,iCount,bIsHaveEllipsis);
	if (0>iCount || strlen(pContent)<=iCount)
	{
		if (pReturnPos)
			*pReturnPos = strlen(pContent);

		return;
	}

	if (bIsHaveEllipsis && length<iCount+4)
		iCount = length-4;

	int iReturnPos = 0;
	if (0x80 >= *(pContent + iCount)  &&  0 <= *(pContent + iCount))
	{
		if (bIsHaveEllipsis)
		{
			memcpy(pContent + iCount, "...", sizeof("..."));
			*(pContent + iCount + sizeof("..."))=0;
			iReturnPos = iCount + sizeof("...");
		}
		else
		{
			*(pContent + iCount)=0;
			iReturnPos = iCount;
		}
		//SIXLog("subChineseChar (a) iCount.[%d],[%s]", iCount,pContent);
	}
	else
	{
		int iIndex = iCount;
		while (0 <= iIndex)
		{
			// 查找从截断位置往前走，有多少个非基本字符（如汉字）
			if (0 > *(pContent + iIndex)  ||  0x80 < *(pContent + iIndex))
				--iIndex;
			else
				break;
		}

		// 从查找到的数目来确定当前要置0的位置，是汉字两字节的前面一个字节还是后一个字节
		//SIXLog("subChineseChar (b) iIndex.[%d],iCount.[%d],[%s]",iIndex, iCount,pContent);
		iIndex = (0==(iCount-iIndex)%2) ? -1 : 0;
		iIndex = iCount + iIndex;

		if (bIsHaveEllipsis)
		{
			memcpy(pContent + iIndex, "...", sizeof("..."));
			*(pContent + iIndex + sizeof("..."))=0;
			iReturnPos = iIndex + sizeof("...");
		}
		else
		{
			*(pContent + iIndex)=0;
			iReturnPos = iIndex;
		}
		//SIXLog("subChineseChar (b) iIndex.[%d],iCount.[%d],[%s]",iIndex, iCount,pContent);
	}

	if (pReturnPos)
		*pReturnPos = iReturnPos;
}

const char *SIX_Utility::GetAppBasePath(const char *folder)
{
	CCString *pAppBasePath = 0;
#ifdef WIN32
	TCHAR tmp_path[1024]={0};
	memset(tmp_path,0,sizeof(tmp_path));
	GetModuleFileName(0,tmp_path, 1023);

	string szDir(SIX_Utility::GetInstance()->UnicodeToUtf8(tmp_path));

	int o1;
	o1=szDir.rfind('\\');

	if (folder && strlen(folder))
		pAppBasePath = CCString::createWithFormat("%s\\%s\\",szDir.substr(0,o1).c_str(),folder);
	else
		pAppBasePath = CCString::createWithFormat("%s\\",szDir.substr(0,o1).c_str());
#else
	if (folder && strlen(folder))
		pAppBasePath = CCString::createWithFormat("%s/%s/",CCFileUtils::sharedFileUtils()->getWriteablePath().c_str(),folder);
	else
		pAppBasePath = CCString::createWithFormat("%s/",CCFileUtils::sharedFileUtils()->getWriteablePath().c_str());
#endif
	return pAppBasePath->getCString();
}

string SIX_Utility::NumTostring(long long Num)   
{
	char buffer[40]={0};
	sprintf(buffer,"%lld",Num);
	string strBuf=buffer;

	return strBuf;
}

string SIX_Utility::TChipTostring(long long Chip, int iCount, const char *pReplaceChar)
{
	string str = NumTostring(Chip);
	int iIndex = iCount;
	int iOffsetIndex = (0<=Chip ? 0 : -1); // 针对负号
	while (str.size()+iOffsetIndex > iIndex)
	{
		str.insert(str.size()-iIndex, pReplaceChar);
		iIndex = iIndex+iCount+1;
	}
	return str;
}

string SIX_Utility::TChipTostring(long long Chip, int &iKWM, long long &t1, long long &t2, string &strKWM, bool drop0)
{
	if(Chip<10000 && Chip>-10000)
	{
		iKWM=0;
		return NumTostring(Chip);
	}

	if((Chip<=-10000 && Chip>-100000000)  ||  (Chip>=10000 && Chip<100000000))
	{
		long long t=Chip/10000;
		//t1= (Chip-t*10000)/10;
		//strKWM="W";
		string ret;
		string strDecimalLeft = NumTostring(t);
		int iLength = strDecimalLeft.length();
		if (0 > Chip)
			iLength--;

		if (4 <= strDecimalLeft.length())
		{
			ret = strDecimalLeft + "W";
		}
		else
		{
			if (drop0)
			{
				if (subNumber(Chip, iLength, 4) == "0")
				{
					ret = strDecimalLeft + "W";
				}
				else
				{
					ret = strDecimalLeft + "." + subNumber(Chip, iLength, strDecimalLeft.length()+1) + "W";
				}
			}
			else
			{
				ret = strDecimalLeft + "." + subNumber(Chip, iLength, 4) + "W";
			}
		}
			
		//iKWM=2;
		return ret;
	}
	if ((Chip <= -100000000) || (Chip >= 100000000))
	{
		long long t = Chip / 100000000;
		//t1= (Chip-t*100000000)/100000;
		//strKWM="M";
		string ret;
		string strDecimalLeft = NumTostring(t);
		int iLength = strDecimalLeft.length();
		if (0 > Chip)
			iLength--;

		if (4 <= strDecimalLeft.length())
			ret = strDecimalLeft + "M";
		else
		{
			if (drop0)
			{
				if (subNumber(Chip, iLength, 4) == "0")
				{
					ret = strDecimalLeft + "M";
				}
				else
				{
					ret = strDecimalLeft + "." + subNumber(Chip, iLength, strDecimalLeft.length() + 1) + "M";
				}
			}
			else
			{
				ret = strDecimalLeft + "." + subNumber(Chip, iLength, 4) + "M";
			}
		}
		//iKWM=3;
		return ret;
	}
	iKWM=-1;
	return "";
}

string SIX_Utility::TChipTostringEx(long long Chip,int &iKWM,long long &t1,long long &t2,string &strKWM)   
{
	if(Chip<10000 && Chip>-10000)
	{
		iKWM=0;
		return NumTostring(Chip);
	}

	if((Chip<=-10000 && Chip>-100000000)  ||  (Chip>=10000 && Chip<100000000))
	{
		long long t=Chip/10000;
		//t1= (Chip-t*10000)/10;
		//strKWM="万";
		string ret;
		string strDecimalLeft = NumTostring(t);
		int iLength = strDecimalLeft.length();
		if (0 > Chip)
			iLength--;

		if (4<=strDecimalLeft.length())
			ret=strDecimalLeft+"万";
		else
			ret=strDecimalLeft+"."+subNumber(Chip, iLength, 4)+"万";
		//iKWM=2;
#if (CC_TARGET_PLATFORM==CC_PLATFORM_WIN32)
		ret = SIX_Utility::GetInstance()->G2U(ret.c_str());
#endif
		return ret;
	}
	if((Chip<=-100000000)  ||  (Chip>=100000000))
	{
		long long t=Chip/100000000;
		//t1= (Chip-t*100000000)/100000;
		//strKWM="亿";
		string ret;
		string strDecimalLeft = NumTostring(t);
		int iLength = strDecimalLeft.length();
		if (0 > Chip)
			iLength--;

		if (4<=strDecimalLeft.length())
			ret=strDecimalLeft+"亿";
		else
			ret=strDecimalLeft+"."+subNumber(Chip, iLength, 4)+"亿";
		//iKWM=3;
#if (CC_TARGET_PLATFORM==CC_PLATFORM_WIN32)
		ret = SIX_Utility::GetInstance()->G2U(ret.c_str());
#endif
		return ret;
	}
	iKWM=-1;
	return "";
}

string SIX_Utility::subNumber(long long llNumber, size_t startIndex, size_t Count)
{
	string strDecimalBack = NumTostring(::abs(llNumber));
	string strDecimalRight = strDecimalBack.substr(startIndex, Count-startIndex);
	if (0 >= strDecimalRight.length())
		return string("");

	size_t zeroIndex = strDecimalRight.find("0");
	bool bLastIsZero = ('0' != strDecimalRight.at(strDecimalRight.length()-1));
	bool bFindZeroIsLast=(zeroIndex!=strDecimalRight.length()-1); // 如果找到的零不是最后一位且最后一位不是0，可以忽略
	if (zeroIndex==string::npos || (bFindZeroIsLast && bLastIsZero))
		zeroIndex = Count-startIndex;
	return strDecimalRight.substr(0, MAX(1,(int)zeroIndex));
}

SYSTEMTIME SIX_Utility::TIME_2_SYSTEMTIME(time_t t)
{
    tm temptm = *localtime(&t);
    SYSTEMTIME st = {
		(WORD)(temptm.tm_year+1900),
		(WORD)(temptm.tm_mon + 1),
		(WORD)temptm.tm_wday,
		(WORD)temptm.tm_mday,
		(WORD)temptm.tm_hour,
		(WORD)temptm.tm_min,
		(WORD)temptm.tm_sec,
		0
	};
    return st;
}

time_t SIX_Utility::SYSTEMTIME_2_TIME(const SYSTEMTIME &st)
{
    tm temptm = {
		st.wSecond,
		st.wMinute,
		st.wHour,
		st.wDay,
		st.wMonth-1,
		st.wYear-1900,
		st.wDayOfWeek,
		0,
		0
	};
    return mktime(&temptm);
}

time_t SIX_Utility::TIME_DIFF_TIME(SYSTEMTIME t)
{
	time_t lastTime = SIX_Utility::GetInstance()->SYSTEMTIME_2_TIME(t);
	time_t now = time(0);
	// 当前时间距离上次签到的时间差值(s)
	return now - lastTime;
}


